package com.wjy.game.viewer;

import javax.annotation.Resource;
import javax.swing.*;

import com.wjy.game.service.ClientSocketService;
import org.springframework.stereotype.Component;

import com.wjy.game.setting.ServerSetting;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wjy
 * @date 2025/5/20 16:16
 * @description 服务器设置视图
 */
@Slf4j
@Component
public class ServerSettingViewer extends ClientViewer {

    private JLabel serverLabel = new JLabel("IP地址 ");

    private JTextField serverField = new JTextField(10);

    private JLabel portLabel = new JLabel("端口 ");

    private JTextField portField = new JTextField(10);

    private JButton saveButton = new JButton("保  存");

    private JButton backButton = new JButton("返   回");

    @Resource
    private LoginViewer loginViewer;

    @Resource
    private ServerSetting serverSetting;

    @Resource
    private ClientSocketService connectService;

    @Override
    protected void repaintUI() {
        serverLabel.setBounds(50, 50, 50, 30);
        add(serverLabel);
        serverField.setBounds(100, 50, 150, 30);
        add(serverField);

        portLabel.setBounds(50, 100, 50, 30);
        add(portLabel);
        portField.setBounds(100, 100, 150, 30);
        add(portField);

        saveButton.setBounds(25, 250, 250, 30);
        add(saveButton);
        backButton.setBounds(195, 290, 80, 30);
        add(backButton);

        serverSetting.load();
        serverField.setText(serverSetting.getIp());
        portField.setText(String.valueOf(serverSetting.getPort()));
    }

    @Override
    protected void actions() {
        backButton.addActionListener(e -> {
            this.setVisible(false);
            loginViewer.initUI();
        });
        saveButton.addActionListener(e -> {
            serverSetting.setIp(serverField.getText());
            serverSetting.setPort(Integer.parseInt(portField.getText()));
            serverSetting.save();
            log.info("保存成功");
            JOptionPane.showMessageDialog(null, "保存成功");
            boolean isConnect = connectService.reconnect();
            if (!isConnect) {
                JOptionPane.showMessageDialog(null, "连接服务器失败！", "提示", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "连接服务器成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        });
    }

    @Override
    public int getWidth() {
        return 300;
    }

    @Override
    public int getHeight() {
        return 400;
    }
}
